<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               ref="crud"
               v-model="form"
               :permission="permissionList"
               :search.sync="search"
               @row-del="rowDel"
               @row-update="rowUpdate"
               @row-save="rowSave"
               :before-open="beforeOpen"
               :page="page"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.user_delete"
                   @click="handleDelete">删 除
        </el-button>
        <el-button type="primary"
                   size="small"
                   plain
                   icon="el-icon-refresh"
                   @click="handleReset">密码重置
        </el-button>
      </template>
      <template slot="menu" slot-scope="{row}">
<!--        <el-button size="small"-->
<!--                   v-if="[1].includes(row.status)"-->
<!--                   type="text"-->
<!--                   icon="el-icon-position"-->
<!--                   @click="handleAssign(row)">今日派单-->
<!--        </el-button>-->
        <el-button size="small"
                   type="text"
                   @click="handleToDetail(row)">详情
        </el-button>
      </template>
    </avue-crud>
    <el-dialog title="订单列表"
               append-to-body
               :visible.sync="ordersBox"
               :before-close="handleMembersClose"
               width="80%">
      <avue-crud :option="ordersOption"
                 :table-loading="loading"
                 :data="ordersData"
                 :page="orderPage"
                 :search.sync="orderSearch"
                 ref="crud"
                 @search-change="ordersSearchChange"
                 @search-reset="ordersSearchReset"
                 @selection-change="ordersSelectionChange"
                 @size-change="ordersSizeChange"
                 @on-load="ordersOnLoad">
<!--        <template slot="search" slot-scope="{row,size}">-->
<!--          <div class="el-col el-col-6 el-col-offset-0 el-col-xs-24 el-col-sm-12 el-col-md-6 avue-form__row"-->
<!--               style="padding-left: 10px; padding-right: 10px;"-->
<!--          >-->
<!--            <div class="el-form-item el-form-item&#45;&#45;small avue-form__item&#45;&#45;">-->
<!--              <label class="el-form-item__label" style="width: 80px;">地址：</label>-->
<!--              <el-input v-model="searchAddress"-->
<!--                        placeholder="地址"-->
<!--                        style="margin-right: 10px; width: 200px !important; height: 32px; line-height: 32px;"-->
<!--                        clearable-->
<!--              ></el-input>-->
<!--            </div>-->
<!--          </div>-->
<!--        </template>-->
        <template slot="menuLeft">
          <el-button type="primary"
                     size="small"
                     icon="el-icon-position"
                     @click="handleAssignToDeliver">派 单
          </el-button>
        </template>
        <template slot-scope="{row}" slot="status">
          <el-tag v-if="row.status === 1" type="success">正常</el-tag>
          <el-tag v-if="row.status === 2 && row.cancelConfirmTime !== ''" type="danger">已取消</el-tag>
          <el-tag v-if="row.status === 2 && row.cancelConfirmTime === ''" type="warning">取消未确认</el-tag>
        </template>
        <template slot-scope="{row}" slot="deliveryStatus">
          <el-tag v-if="row.deliveryStatus === 0" type="primary">待配送</el-tag>
          <el-tag v-else-if="row.deliveryStatus === 1" type="warning">配送中
            <span v-if="row.sendDeliverName && row.sendDeliverName !== ''"> 【{{ row.sendDeliverName }}】</span>
          </el-tag>
          <el-tag v-else-if="row.deliveryStatus === 99" type="success">配送完成
            <span v-if="row.completeDeliverName && row.completeDeliverName !== ''"> 【{{ row.completeDeliverName }}】</span>
          </el-tag>
          <el-tag v-else type="danger">未知</el-tag>
        </template>
        <template slot-scope="{row}" slot="isGeneral">
          <el-tag v-if="row.isGeneral === 1" type="primary">标准餐</el-tag>
          <el-tag v-else-if="row.isGeneral === 2" type="warning">个性餐</el-tag>
          <el-tag v-else type="danger">未知</el-tag>
        </template>
      </avue-crud>
    </el-dialog>
    <el-dialog title="订单列表"
               append-to-body
               :visible.sync="detailShow"
               :before-close="handleDetailClose"
               width="85%">
      <send-order :row="detailRow"></send-order>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getList,
  getUser,
  remove,
  update,
  add,
  grant,
  resetPassword
} from "@/api/system/user";
import {getRoleTree} from "@/api/system/role";
import {mapGetters} from "vuex";
import website from '@/config/website';
import { getList as deliveryList } from "@/api/delivery/delivery";
import CustomerServicePayment from "../system/customer_service_payment";
import SendOrder from "./components/send_order";
import {dateFormat} from "@/util/date";
import { assignOrders } from "@/api/merchant/deliver";

const customerServiceRoleId = '1806333055418417154'
export default {
  components: {CustomerServicePayment, SendOrder},
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        callback();
      }
    };
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      searchName: '',
      searchAddress: '',
      mealOptions: [
        {
          value: '1',
          label: 'A餐'
        }, {
          value: '2',
          label: 'B餐'
        }
      ],
      form: {},
      search:{},
      deliverId: '',
      mode: '',
      roleBox: false,
      ordersBox: false,
      paymentBox: false,
      paymentRow: {},
      ordersSelectionList: [],
      ordersOption: {
        height: 'auto',
        calcHeight: 210,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        menuWidth: 100,
        // expand: true,
        selection: true,
        refreshBtn: false,
        columnBtn: false,
        menu: false,
        column: [
          {
            label: "编号",
            prop: "originNo",
            width: '160px',
            overHidden: true,
          },
          {
            label: "门店",
            prop: "merchantId",
            type: "select",
            dicUrl: '/api/merchant/merchant/select',
            props: {
              label: "name",
              value: "id"
            },
          },
          {
            label: "收件人",
            prop: "receiverName",
            slot: true,
            overHidden: true,
          },
          {
            label: "电话",
            prop: "receiverPhone",
            width: '100px',
          },
          {
            label: "地址",
            prop: "receiverAddress",
            width: '200px',
            search: true,
            overHidden: true,
          },
          {
            label: "日期",
            prop: "date",
            width: '100px',
          },
          {
            label: "午B餐",
            prop: "meal",
            type: 'radio',
            search: true,
            dicData: [
              {
                label: "A餐",
                value: 1
              },
              {
                label: "B餐",
                value: 2
              },
            ],
          },
          {
            label: "状态",
            width: 150,
            prop: "status",
            slot: true,
            display: false
          },
          {
            label: "配送状态",
            prop: "deliveryStatus",
            slot: true,
          },
          {
            label: "托寄物",
            prop: "depositum",
            rules: [{
              required: true,
              message: "请输入托寄物",
              trigger: "blur"
            }]
          },
          {
            label: "订单备注",
            prop: "orderRemark",
            width: 200,
            overHidden: true,
            rules: [{
              required: true,
              message: "请输入订单备注",
              trigger: "blur"
            }]
          },
          {
            label: "扩展字段1",
            prop: "remark1",
            overHidden: true,
            rules: [{
              required: true,
              message: "请输入扩展字段1",
              trigger: "blur"
            }]
          },
          {
            label: "创建时间",
            prop: "createTime",
            overHidden: true,
            display: false,
          },
          {
            label: "最后更新时间",
            prop: "updateTime",
            overHidden: true,
            display: false,
          },
        ]
      },
      ordersData: [],
      loading: true,
      selectionList: [],
      query: {},
      page: {
        pageSize: 100,
        currentPage: 1,
        total: 0
      },
      orderSearch: {
        deliveryStatus: '0',
      },
      orderPage: {
        pageSize: 100,
        currentPage: 1,
        total: 0
      },
      props: {
        label: "title",
        value: "key"
      },
      roleGrantList: [],
      roleTreeObj: [],
      option: {
        height: 'auto',
        calcHeight: 210,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        selection: true,
        viewBtn: false,
        column: [
          {
            label: "账号",
            prop: "account",
            search: true,
            rules: [{
              required: true,
              message: "请输入账号",
              trigger: "blur"
            }],
            span: website.tenantMode ? 12 : 24,
          },
          {
            label: "门店",
            prop: "merchantId",
            type: "select",
            dicUrl: '/api/merchant/merchant/select',
            props: {
              label: "name",
              value: "id"
            },
            rules: [{
              required: true,
              message: "请输入账号",
              trigger: "blur"
            }],
          },
          {
            label: '密码',
            prop: 'password',
            hide: true,
            editDisplay: false,
            viewDisplay: false,
            rules: [{required: true, validator: validatePass, trigger: 'blur'}]
          },
          {
            label: '确认密码',
            prop: 'password2',
            hide: true,
            editDisplay: false,
            viewDisplay: false,
            rules: [{required: true, validator: validatePass2, trigger: 'blur'}]
          },
          {
            label: "姓名",
            prop: "realName",
            search: true,
            rules: [{
              required: true,
              message: "请输入用户姓名",
              trigger: "blur"
            }]
          },
          {
            label: "手机号码",
            prop: "phone",
            rules: [{
              required: true,
              message: "请输入手机号码",
              trigger: "blur"
            }],
            overHidden: true
          },
          {
            label: "账号状态",
            prop: "statusName",
            hide: true,
            display: false
          }
        ]
      },
      data: [],
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '模板上传',
            prop: 'excelFile',
            type: 'upload',
            drag: true,
            loadText: '模板上传中，请稍等',
            span: 24,
            propsHttp: {
              res: 'data'
            },
            tip: '请上传 .xls,.xlsx 标准格式文件',
            action: "/api/blade-user/import-user"
          },
          {
            label: '模板下载',
            prop: 'excelTemplate',
            formslot: true,
            span: 24,
          }
        ]
      },
      detailRow: {},
      detailShow: false,
    };
  },
  computed: {
    ...mapGetters(["userInfo", "permission"]),
    permissionList() {
      return {
        addBtn: true,
        delBtn: false,
        editBtn: true
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    orderIds() {
      let ids = [];
      this.ordersSelectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  methods: {
    handleMembersClose() {
      this.ordersBox = false
      this.mode = ''
      this.deliverId = ''
      this.ordersData = []
      this.orderPage.total = 0
      this.ordersSelectionList = []
      this.onLoad(this.page)
    },
    handleToDetail(row) {
      this.detailRow = row
      this.detailShow = true
    },
    handleDetailClose() {
      this.detailShow = false
      this.detailRow = {}
      this.onLoad(this.page)
    },
    handleAssign(row) {
      this.deliverId = row.id
      this.mode = 'add'
      this.ordersBox = true
      this.ordersOnLoad(this.orderPage)
    },
    handleSearch() {
      this.orderPage.currentPage = 1
      this.ordersOnLoad(this.orderPage)
    },
    ordersOnLoad(page, params = {}) {
      this.loading = true;
      params.startDate = dateFormat(new Date())
      params.endDate = dateFormat(new Date())
      if (this.searchAddress && this.searchAddress !== "") {
        params.address = this.searchAddress
      }
      if (this.orderSearch.deliveryStatus && this.orderSearch.deliveryStatus !== "") {
        params.deliveryStatus = this.orderSearch.deliveryStatus
      }
      deliveryList(page.currentPage, page.pageSize, params).then(res => {
        const data = res.data.data;
        this.orderPage.total = data.total;
        this.ordersData = data.records;
        this.loading = false;
      });
    },
    ordersSizeChange(pageSize) {
      this.orderPage.pageSize = pageSize;
    },
    ordersSearchReset() {
      this.searchAddress = "";
      this.orderSearch = {
        deliveryStatus: '0'
      }
      this.ordersOnLoad(this.orderPage);
    },
    ordersSearchChange(params, done) {
      this.orderPage.currentPage = 1;
      this.ordersOnLoad(this.orderPage, params);
      done();
    },
    ordersSelectionChange(list) {
      this.ordersSelectionList = list;
    },
    handleAssignToDeliver() {
      if (this.orderIds.length === 0) {
        this.$message.warning('请至少选择一个订单！')
        return
      }
      assignOrders(this.deliverId, this.orderIds).then(() => {
        this.ordersOnLoad(this.orderPage);
      })
    },
    rowSave(row, done, loading) {
      row.roleId = customerServiceRoleId
      row.name = row.account
      add(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      row.roleId = customerServiceRoleId
      update(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    handleReset() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择账号密码重置为123456?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return resetPassword(this.ids);
        })
        .then(() => {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getUser(this.form.id).then(res => {
          this.form = res.data.data;
          if(this.form.hasOwnProperty("roleId")){
            this.form.roleId = this.form.roleId.split(",");
          }
        });
      }
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      params.roleId = customerServiceRoleId
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
      });
      getRoleTree(this.form.tenantId).then(res => {
        const column = this.findObject(this.option.column, "roleId");
        column.dicData = res.data.data;
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.el-form-item {
  margin-right: 20px;
}
.el-input__icon {
  height: auto;
}
.avue-crud .el-input__inner, .avue-form .el-input__inner {
  height: 32px;
}
.success-row{
  background-color: #b4e59e !important;
  color: #000000;
}
</style>
